﻿using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System;

namespace GermaneShanidze.Applications.Jokeri.LobbyWcfService
{
    public class LobbyUserService : ILobbyUserService
    {
        public ObservableCollection<FacebookUserInfo> GetActiveUsers(FacebookUserInfo facebookUserInfo)
        {
            #region Retrive ActiveUser list from Context and return in ObservableCollection
            ObservableCollection<FacebookUserInfo> retVal = new ObservableCollection<FacebookUserInfo>();
            using (var activeUsersContext = new JokeriActiveUserEntities())
            {
                #region Update ActiveUsers list
                ActiveUser au;
                // Check if we are already in ActiveUsers List
                if ((from activeUsers in activeUsersContext.ActiveUsers
                           where activeUsers.Id == facebookUserInfo.UserId
                           select activeUsers).Count() > 0)
                {
                    // We are present. Retrieve record
                    au = (from activeUsers in activeUsersContext.ActiveUsers
                          where activeUsers.Id == facebookUserInfo.UserId
                          select activeUsers).First();
                    // Update date
                    au.LastUpdated = DateTime.Now;
                }
                else
                {
                    // We are not present. Create new record 
                    au = new ActiveUser()
                    {
                        Id = facebookUserInfo.UserId,
                        FirstName = facebookUserInfo.FirstName,
                        LastName = facebookUserInfo.LastName,
                        ProfilePictureUrl = facebookUserInfo.ProfilePictureUrl,
                        LastUpdated = DateTime.Now
                    };
                    activeUsersContext.AddToActiveUsers(au);
                }
                activeUsersContext.SaveChanges();
                #endregion Update ActiveUsers list

                // Retrieve all records
                foreach (var activeusersQuery in from users in activeUsersContext.ActiveUsers
                                                select users)
                {
                    FacebookUserInfo fui = new FacebookUserInfo();
                    fui.UserId = (long)activeusersQuery.Id;
                    fui.FirstName = activeusersQuery.FirstName;
                    fui.LastName = activeusersQuery.LastName;
                    fui.ProfilePictureUrl = activeusersQuery.ProfilePictureUrl;
                    retVal.Add(fui);
                }
            }
            return retVal;
            #endregion Retrive ActiveUser list from Context and return in ObservableCollection
        }
    }
}
